package com.tenbent.product.base.enums.base;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import com.tenbent.product.base.utils.EnumUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.UnmodifiableMap;

/**
 * @author lihh
 * @since 2016/4/26
 */
public class EnumPool {

	private static Map<String, Map<Integer, BaseEnum>> POOL = new HashMap<>();

	public static void addEnum(String name, BaseEnum baseEnum) {
		Map<Integer, BaseEnum> map = POOL.get(name);
		if (map == null) {
			map = new TreeMap<>((key1, key2) -> {
				return key1.compareTo(key2);
			});
			POOL.put(name, map);
		}
		map.put(baseEnum.getValue(), baseEnum);
	}

	public static void addEnums(String name, BaseEnum[] baseEnums) {
		Map<Integer, BaseEnum> map = POOL.get(name);
		if (map == null) {
			map = new TreeMap<>((key1, key2) -> {
				return key1.compareTo(key2);
			});
			POOL.put(name, map);
		}
		for (BaseEnum baseEnum : baseEnums) {
			map.put(baseEnum.getValue(), baseEnum);
		}
	}

	public static void addEnums(String name, Class<? extends BaseEnum> clazz) {
		addEnums(name, EnumUtil.getEnums(clazz));
	}

	public static Map<Integer, BaseEnum> getEnums(String name) {
		Map<Integer, BaseEnum> map = POOL.get(name);
		if (map == null) {
			map = MapUtils.EMPTY_MAP;
		} else {
			map = UnmodifiableMap.decorate(map);
		}
		return map;
	}

	public static <T> T getEnum(String name, Integer value) {
		return (T) getEnums(name).get(value);
	}
}
